package com.hrms.hrms_employee.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrms.common.entity.BaseEntity;
import com.hrms.common.service.RsaProperties;
import com.hrms.common.utils.RSAUtils;
import com.hrms.common.vo.ResultMessage;
import com.hrms.hrms_employee.dao.StaffCheckDao;
import com.hrms.hrms_employee.dao.StaffDetailDao;
import com.hrms.hrms_employee.entity.*;
import com.hrms.hrms_employee.service.*;
import com.hrms.hrms_employee.vo.CheckVO;
import com.hrms.hrms_employee.vo.StaffDetailAttachmentVO;
import com.hrms.hrms_employee.vo.SysUsr;
import com.hrms.hrms_employee.vo.staffDetailVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 员工个人信息表(StaffDetail)表服务实现类
 *
 * @author makejava
 * @since 2025-01-17 17:14:23
 */
@Service("staffDetailService")
public class StaffDetailServiceImpl extends ServiceImpl<StaffDetailDao, StaffDetail> implements StaffDetailService {
    @Autowired
    private StaffDetailDao staffDetailDao;
    @Autowired
    private EntryClient entryClient;
    @Autowired
    private OssClient ossClient;
    @Autowired
    private StaffDetailAttachmentService service;
    @Autowired
    private StaffPositionService staffPositionService;
    @Autowired
    private StaffContractService staffContractService;
    @Autowired
    private SecurityClient securityClient;
    @Autowired
    private StaffCheckDao staffCheckDao;
    @Override
    public staffDetailVO SelectStaffDetail(Long id) {
        staffDetailVO staffDetailVO = this.staffDetailDao.SelectStaffDetail(id);
        return staffDetailVO;
    }

    @Override
    @Transactional
    public boolean saveDetailAndStartFlow(Map<String, String> map, MultipartFile photo, MultipartFile contractFile, List<StaffDetailAttachmentVO> attachments) {
        //保存入职信息
        //保存数据到staffDetaillVO
        staffDetailVO staffDetailVO = new staffDetailVO();
        try {
            staffDetailVO = this.initStaffDetailVar(map);
        }catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //保存图片数据到oss云服务
//        String photo = staffDetailVO.getPhoto();
        ResultMessage message = this.ossClient.uploadFile(photo, "photo/");
        String url = (String) message.getData();
        staffDetailVO.setPhoto(url);
        List<StaffPosition> positions = this.staffPositionService.selectDepartmentStaffs(14L);
        StaffPosition staffPosition = positions.get(ThreadLocalRandom.current().nextInt(positions.size())); 
        StaffDetail staffDetail = new StaffDetail();

        BeanUtils.copyProperties(staffDetailVO,staffDetail);
        this.save(staffDetail);
        staffDetailVO.setId(staffDetail.getId());
//        staffDetailVO.getStaffDetailAttachmentVO()(staffDetail.getId());
        //遍历持久化staffDetailAttachmentVO
        List<StaffDetailAttachment> attachmentList = new ArrayList();
        attachments.forEach(staffDetailAttachmentVO -> {
            StaffDetailAttachment staffDetailAttachment = new StaffDetailAttachment();
            staffDetailAttachment.setState(0);
            staffDetailAttachment.setIsDeleted(0);
            ResultMessage resultMessage = this.ossClient.uploadFile(staffDetailAttachmentVO.getAttachment(), "attachments/");
            //设置url
            staffDetailAttachment.setAttachment((String) resultMessage.getData());
            //设置info
            staffDetailAttachment.setInfo(staffDetailAttachmentVO.getInfo());
            staffDetailAttachment.setStaffDetailId(staffDetail.getId());
            this.service.save(staffDetailAttachment);
            //添加到List<StaffDetailAttachment>
            attachmentList.add(staffDetailAttachment);
        });
        //保存合同信息
        StaffContract staffContract = new StaffContract();
        try {
            staffContract = this.initStaffContractVar(map,staffDetailVO);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        ResultMessage message2 = this.ossClient.uploadFile(contractFile, "contracts/");
        staffContract.setAttachment((String) message2.getData());
        staffContract.setStaffId(staffDetail.getId());
        this.staffContractService.save(staffContract);
        //staffPosition保存
        Long staffPositionId = this.staffPositionSave(staffDetailVO, staffContract);
        this.update(new UpdateWrapper<StaffDetail>().eq("id",staffDetail.getId()).set("staff_id",staffPositionId));
        //初始化
        HashMap<String, Object> hashmap = this.initVar(staffPosition, staffDetailVO,staffContract);
        ResultMessage resultMessage = this.entryClient.entryStart(hashmap);
        return true ? resultMessage.getResult() == 200 : false;
    }
    //staffPosition保存
    private Long staffPositionSave(staffDetailVO staffDetailVO, StaffContract staffContract) {
        //搜索当前最新staffPosition

        StaffPosition staffPosition = new StaffPosition();
        staffPosition.setName(staffDetailVO.getName());
        staffPosition.setPhone(staffDetailVO.getPhone());
        staffPosition.setDepartment(staffContract.getDepartment());
        staffPosition.setStation(staffContract.getStation());
        staffPosition.setJobNumber("ZP200012");
        staffPosition.setState(0);
        this.staffPositionService.save(staffPosition);
        return staffPosition.getId();
    }

    /**
     * 更新并新建账号
     *
     * @param
     * @return
     */
    @Override
    public ResultMessage updateDetails(String id) throws Exception {
        //RSA解密
        SysUsr sysUsr  = this.staffDetailDao.selectSysUsrById(Long.parseLong(id));
        String pwd = RSAUtils.encryptByPublic("1234", RsaProperties.publicKey);
        sysUsr.setSysUsrPassword(pwd);
        this.securityClient.usrRegister(sysUsr);
        return new ResultMessage(ResultMessage.Success,"");
    }

    /**
     * 打卡
     * @param checkVO
     */
    @Override
    public void check(CheckVO checkVO) throws ParseException {
        //判断是否已经打过卡
        List<CheckVO> vo = this.staffDetailDao.selectCheck(checkVO.getUserId(), new Date());
        LocalTime now = LocalTime.now();
        LocalTime startTime = LocalTime.of(9, 0); // 早上9点
        LocalTime endTime = LocalTime.of(18, 0); // 晚上6点
        Boolean ifNormal = !now.isBefore(startTime) && !now.isAfter(endTime);
        if (vo.size() > 0) {
            //如果存在数据，证明打过卡
            if (vo.size() == 1) {
                //只打过早卡
            }else {
                //打过两次或者两次以上的打卡，覆盖第二次打卡
                StaffCheck staffCheck2 = new StaffCheck();
                BeanUtils.copyProperties(vo.get(1),staffCheck2);
                staffCheck2.setCheckInTime(checkVO.getCheckInTime());
                staffCheck2.setType("正常签退");
                if (ifNormal) {
                    //早退
                    staffCheck2.setType("早退");
                }
                this.staffCheckDao.updateById(staffCheck2);
                return;
            }

        }
        checkVO.setType("正常签到");
        if (ifNormal) {
            //迟到了
            checkVO.setType("迟到");
        }
        StaffCheck staffCheck = new StaffCheck();
        BeanUtils.copyProperties(checkVO,staffCheck);
        this.staffCheckDao.insert(staffCheck);
    }

    @Override
    public List<CheckVO> checklist() {
        return this.staffCheckDao.selectList();
    }

    /**
     * 初始化StaffContract
     *
     * @param map
     * @param staffDetailVO
     * @return
     */
    private StaffContract initStaffContractVar(Map<String, String> map, staffDetailVO staffDetailVO) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        StaffContract staffContract = new StaffContract();
        staffContract.setStaffId(staffDetailVO.getId());
//        staffContract.setDepartment(staffDetailVO.g);
        staffContract.setDepartment(map.get("department"));
        staffContract.setStation(map.get("position"));
        staffContract.setCompensation(Double.parseDouble(map.get("compensation")));
        staffContract.setContract(Integer.parseInt(map.get("contractType")));
        staffContract.setDuration(Integer.parseInt(map.get("contractYears")));
        staffContract.setStartDate(simpleDateFormat.parse(map.get("startDate")));
        staffContract.setSignDate(simpleDateFormat.parse(map.get("signDate")));
        staffContract.setExpirationDate(simpleDateFormat.parse(map.get("endDate")));
        return staffContract;

//        staffContract.setId("11"+UUID.randomUUID());
    }

    /**
     * 初始化staffDetailVO
     * @param map
     * @return
     */
    private staffDetailVO initStaffDetailVar(Map<String, String> map) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        staffDetailVO staffDetailVO = new staffDetailVO();
        staffDetailVO.setName(map.get("name"));                  // 姓名：张操
        staffDetailVO.setAddress(map.get("address"));           // 地址：苏州
        staffDetailVO.setBirthDate(simpleDateFormat.parse(map.get("birthDate"))); // 出生日期：2001-02-08
        staffDetailVO.setCensus(Integer.parseInt(map.get("census")));     // 户籍类型：2
        staffDetailVO.setEducation(map.get("education")); // 教育程度：3
        staffDetailVO.setGender(Integer.parseInt(map.get("gender")));    // 性别：1
        staffDetailVO.setGraduate(map.get("graduate"));          // 毕业院校：苏科大
        staffDetailVO.setGraduationDate(simpleDateFormat.parse(map.get("graduationDate"))); // 毕业时间：2025-03-20
        staffDetailVO.setHouseholdLocation(map.get("householdLocation")); // 户籍地：户籍
        staffDetailVO.setIdNumber(map.get("idNumber"));           // 身份证号：320829200201200816
        staffDetailVO.setMail(map.get("mail"));                  // 邮箱：asdf1716264645@163.com
        staffDetailVO.setMarital(Integer.parseInt(map.get("marital"))); // 婚姻状况：2
        staffDetailVO.setNation(map.get("nation"));  // 民族：2
        staffDetailVO.setPhone(map.get("phone"));                 // 电话：18962549150
        staffDetailVO.setPolitic(map.get("politic")); // 政治面貌：2
        staffDetailVO.setStaffNative(map.get("staffNative"));     // 籍贯：籍贯
        staffDetailVO.setWorkDate(simpleDateFormat.parse(map.get("workDate"))); // 工作日期：2025-03-12
        staffDetailVO.setIsDeleted(Integer.parseInt(map.get("isDeleted"))); // 删除标记：0
        staffDetailVO.setState(Integer.parseInt(map.get("state")));    // 状态：0
        return staffDetailVO;
    }


    private HashMap<String, Object> initVar(StaffPosition staffPosition, staffDetailVO staffDetailVO, StaffContract staffContract) {
        HashMap<String, Object> map = new HashMap<>();
        //hr
        map.put("hr",staffPosition.getName());
        //获取所在部门总经理总经理
        map.put("manager","lisi");
        //提交人
        map.put("initiator",staffDetailVO.getName());
        map.put("director","lisi");
        //表单
        map.put("staffDetailVO",String.valueOf(staffDetailVO.getId()));
        return map;
    }
}

